import urllib
import urllib2
import json
import sys
import random

# Navigation functions
def getPageContent(params, url, destination, cookie=None):
    con = urllib2.Request(url+destination, params)
    if (cookie != None):
        con.add_header('cookie', cookie)
    response = urllib2.urlopen(con)
    cookie = response.headers.get('Set-Cookie')
    reader = response.read()
    print reader
    json_array = json.loads(reader)
    return json_array,cookie

def getStart(name, url, destination):
    params = urllib.urlencode({'name': name})
    return getPageContent(params, url, destination)

def guessWord(word, status, cookie, url, destination):
    params = urllib.urlencode({'word': word, 'type': 'add', 'buddha': status})
    return getPageContent(params, url, destination, cookie)

def guessRuleGet(rule, cookie, url, destination):
    params = urllib.urlencode({'type': 'guessGet'})
    return getPageContent(params, url, destination, cookie)
    
def guessRulePost(rule, wordsAndStatus, cookie, url, destination):
    params = urllib.urlencode({'rule:': rule, 'wordsAndStatus': 'blah', 'type': 'guessPost'})
    for key in wordsAndStatus.keys():
        params += '&' + urllib.urlencode({key: wordsAndStatus[key]})
    return getPageContent(params, url, destination, cookie)

class Player():

    def __init__(self, name, threshold, wordsfile, url, destination):
        self.name = name
        self.threshold = threshold
        fin = open(wordsfile, "r")
        self.words = []
        for line in fin:
            self.words.append(line.rstrip())
        fin.close()
        self.url = url
        self.destination = destination

    # Game-logic functions
    def applyRule(self, rule, word):
        return random.choice([True, False])
        
    def chooseWord(self, words, rule=None):
        return random.choice(words)
        
    def hypothesize(self):
        print "Thinking..."
    
    def play(self):
        print "Starting game"
        json_game, cookie = getStart(self.name, self.url, self.destination)
        
        self.oldBuddha = set([])
        self.oldNonBuddha = set([])
        
        while ('game_status' not in json_game):
            self.buddha = set(json_game['buddha']).difference(self.oldBuddha)
            self.nonbuddha = set(json_game['nonbuddha']).difference(self.oldNonBuddha)
            print self.buddha
            print self.nonbuddha
            
            self.hypothesize()
            
            # If we have more than THRESHOLD stones, it's time to start guessing the rule
            if json_game['stones'] > self.threshold:
                print "Time to guess..."
                json_guess, cookie = guessRuleGet(maxRule, cookie, self.url, self.destination)
                wordsAndStatus = {}
                for word in json_guess['words']:
                    status = self.applyRule(maxRule, word)
                    if status:
                        wordsAndStatus[word] = 'buddha'
                    else:
                        wordsAndStatus[word] = 'nonbuddha'
                json_game, cookie = guessRulePost(maxRule, wordsAndStatus, cookie, self.url, self.destination)
                
            self.oldBuddha = self.oldBuddha.union(self.buddha)
            self.oldNonBuddha = self.oldNonBuddha.union(self.nonbuddha)
            
            guess = self.chooseWord(self.words)
            json_game, cookie = guessWord(guess, 1, cookie, self.url, self.destination)
            print json_game
            print "\n"
            print "\n"
        print "We win because we're awesome. We're awesome because we win." 
        
def main():
    p = Player("Random", 10, "words.txt", "http://cs.centenary.edu", "/~mgoadric/zendo-ilp-challenge/agent/zendo.php")
    p.play()
    
main()